package com.atguigu.serviceedu.controller.front;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.serviceedu.client.OrderClient;
import com.atguigu.serviceedu.entity.EduCourse;
import com.atguigu.serviceedu.entity.chapter.ChapterVo;
import com.atguigu.serviceedu.entity.vo.CourseFrontQuery;
import com.atguigu.serviceedu.entity.vo.CourseWebVo;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduCourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author JY
 * @create 2021-02-01 13:27
 */
@RestController
@RequestMapping("/serviceedu/coursefront")
//@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private OrderClient orderClient;

    //条件查询分页
    @PostMapping("page/{page}/{limit}")
    public R pageList(@PathVariable long page, @PathVariable long limit,
                      @RequestBody(required = false)CourseFrontQuery courseFrontQuery){
        Page<EduCourse> pageParam = new Page<>(page,limit);
        Map<String,Object> map = courseService.pageList(pageParam,courseFrontQuery);
        return R.ok().data(map);
    }

    @GetMapping("getCourseInfoById/{courseId}")
    public R getCourseInfoById(@PathVariable String courseId, HttpServletRequest request){
        //得到课程基本信息
        CourseWebVo courseWebVo = courseService.getCourseInfoById(courseId);
        //得到课程章节信息
        List<ChapterVo> chapterVoList = chapterService.getListByCourseId(courseId);

        //远程调用，判断课程是否被购买
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean buyCourse = false;
        if(!StringUtils.isEmpty(memberId)){
            buyCourse = orderClient.isBuyCourse(memberId, courseId);
        }
        return R.ok().data("course", courseWebVo).data("chapterVoList", chapterVoList).data("isbuy",buyCourse);
    }

    @GetMapping("getOrderCourseInfo/{courseId}")
    public com.atguigu.commonutils.vo.CourseWebVo getOrderCourseInfo(@PathVariable String courseId){
        CourseWebVo courseWebVo = courseService.getCourseInfoById(courseId);
        com.atguigu.commonutils.vo.CourseWebVo course = new com.atguigu.commonutils.vo.CourseWebVo();
        BeanUtils.copyProperties(courseWebVo,course);
        return course;
    }
}
